﻿using System;
using System.Collections.Generic;
using System.Linq;
using EasyWeixin.CommonAPIs;
using EasyWeixin.Entities.JsonResult;

using RaceList.activity.help;
using RaceList.activity.util;

namespace RaceList.activity.relay
{
    /// <summary>
    ///     论分部类的好处
    /// </summary>
    public partial class Relayresult
    {
        public Relayresult()
        {
            Chengji = new Chengji();
            LoginUserData = new LoginUserData();
            Paihangs = new List<Paihang>();
            ActivityStatus = ActivityStatus.WeiKaishi;
        }

        #region protected

        public void InitProperty()
        {
            InitActivityStatus();
            InitChengji();
            InitLoginUserData();
            InitWeixinConfig();
        }

        protected void InitWeixinConfig()
        {
            WxConfigResult result = CommonApi.GetWxConfigResult(ActivityConfig.MHalloweenAppId,
                ActivityConfig.MHalloweenAppSecrect, Request.Url.ToString());
            WxConfig = result;
        }

        private void InitChengji()
        {
            Chengji.RelayId = Relay.Id;
            Chengji.Mingci = RelayQuery.GetMingci(Relay);
            Chengji.Baifenbi = RelayQuery.GetBaifenbi(Relay);
            Chengji.SumScore = RelayQuery.GetSumScoreById(Relay.Id);
            Chengji.NickName = Relay.WeixinUser.Nickname;
            Chengji.Helps = RelayQuery.GetHelps(Relay);
            Chengji.IsGameOver = Chengji.Helps.Count >= ActivityConfig.MHalloweenTotalPerson;
            Chengji.IsTop10 = Chengji.Mingci <= 10;
            Chengji.HasAward = RelayQuery.GetActivity_AwardUserIsAward(Relay.Id);
            if (Chengji.IsGameOver && !Chengji.HasAward) //如果游戏结束，并且没有提交过领奖信息
            {
                Activity_AwardUser awardUser = RelayQuery.GetActivity_AwardUser(Relay.Id);
                if (awardUser == null)
                {
                    var obj = new Activity_AwardUser
                    {
                        addTime = DateTime.Now,
                        relayId = Relay.Id,
                        winCode = RelayQuery.GuidTo16String(Guid.NewGuid()),
                    };
                    string winCode = RelayQuery.AddActivity_AwardUser(obj);
                    Chengji.WinCode = winCode;
                }
                else
                {
                    Chengji.WinCode = awardUser.winCode;
                }
            }
        }

        /// <summary>
        ///     如果互动状态为Jiesu的话,从ZongChengji表获取数据
        /// </summary>
        protected void InitActivityStatus()
        {
            ActivityStatus = RelayQuery.GetCycleStatus(Relay.CycleId);
            if (ActivityStatus == ActivityStatus.Jiesu)
            {
                InitPaiHangsFromZongChengji(Relay.CycleId);
            }
            else
            {
                InitPaiHangsFromRelay();
            }
        }

        /// <summary>
        ///     先添加数据，如果添加了就直接获取实例化即可
        /// </summary>
        /// <param name="cycleId"></param>
        private void InitPaiHangsFromZongChengji(int cycleId)
        {
            Paihangs = new List<Paihang>();
            RelayQuery.AddActivityZongChengji(cycleId);

            List<Activity_Relay_ZongChengji> list = RelayQuery.GetActivity_ZongChengji(cycleId);

            int takeNum = list.Count > 10 ? 10 : list.Count;
            foreach (Activity_Relay_ZongChengji item in list.Take(takeNum))
            {
                Paihangs.Add(new Paihang
                {
                    Headimgurl = item.Activity_Relay.WeixinUser.Headimgurl,
                    Nickname = item.Activity_Relay.WeixinUser.Nickname,
                    SumScore = item.Activity_Relay.SumScore,
                    RelayId = item.Activity_Relay.Id,
                });
            }
        }

        private void InitPaiHangsFromRelay()
        {
            Paihangs = new List<Paihang>();
            List<Activity_Relay> list = RelayQuery.GetPaihang();
            foreach (Activity_Relay item in list)
            {
                Paihangs.Add(new Paihang
                {
                    Headimgurl = item.WeixinUser.Headimgurl,
                    Nickname = item.WeixinUser.Nickname,
                    SumScore = item.SumScore,
                    RelayId = item.Id,
                });
            }
        }

        #endregion

        #region LoginUserData

        protected void InitLoginUserData()
        {
            int loginwxid = SessionHelp.UserData.WeixinUserId;

            LoginUserData.CanHelp = InitCanHelp(loginwxid);
            ;

            ipowdb_suibian_webDataContext db = ConnHelper.ipowdb_suibian_web();
            IQueryable<Activity_Relay> list = db.Activity_Relay.Where(s => s.WeixinUserId == loginwxid);
            list.Where(s => s.CycleId == Relay.CycleId).OrderByDescending(s => s.SumScore);
            if (list.Count() > 0)
            {
                LoginUserData.IsPlay = true;
            }

            //得到所有成绩中未完结的最高分的那一条
            //if (LoginUserData.IsPlay)
            //{
            //    LoginUserData.RelayId = RelayQuery.GetBestScore(loginwxid, Relay.CycleId).Id;
            //}
        }

        private bool InitCanHelp(int loginwxid)
        {
            bool canhelp = loginwxid != Relay.WeixinUserId; //如果相等的话，就是自己登录以后查看自己的也不能帮忙
            if (canhelp) //如果==true
            {
                canhelp = Relay.Activity_SubRelay.Count() + 1 < ActivityConfig.MHalloweenTotalPerson; //参与游戏的人少于最大人数为true
                if (canhelp)
                    canhelp = RelayQuery.GetCanHelp(loginwxid, Relay);
            }
            return canhelp;
        }

        #endregion

        #region property

        /// <summary>
        ///     这个这个接力跑活动目前的状态，（未开始，进行中，结束）
        /// </summary>
        protected ActivityStatus ActivityStatus { get; set; }

        /// <summary>
        ///     当前登录用户的一些信息（主要是帮忙的人，但也可是是自己）
        /// </summary>
        protected LoginUserData LoginUserData { get; set; }

        /// <summary>
        ///     活动发起人的成绩信息，拥护者的成绩
        /// </summary>
        protected Chengji Chengji { get; set; }

        /// <summary>
        ///     总成绩的前10名
        /// </summary>
        protected List<Paihang> Paihangs { get; set; }

        protected WxConfigResult WxConfig { get; set; }

        #endregion
    }
}